﻿using System.Collections.Generic;
using NUnit.Framework;

namespace ExtensionMethodExtravaganza.Tests
{
	[TestFixture]
	public class DictionaryExtensionsTests
	{
		[Test]
		public void GetOrCreateTest()
		{
			var a = new object();
			var dic = new Dictionary<string, object> { { "a", a } };

			Assert.AreEqual(1, dic.Count);
			Assert.AreSame(a, dic.GetOrCreate("a"));
			Assert.AreEqual(1, dic.Count);

			var b = dic.GetOrCreate("b");

			Assert.AreEqual(2, dic.Count);
			Assert.AreSame(b, dic.GetOrCreate("b"));
			Assert.AreEqual(2, dic.Count);
		}

		[Test]
		public void GetOrLookUpTest()
		{
			var joe = new Employee { Name = "joe" };
			var employees = new Dictionary<string, Employee> { { "joe", joe } };

			Assert.AreEqual(1, employees.Count);
			Assert.AreSame(joe, employees.GetOrLookUp("joe", FindEmployee));
			Assert.AreEqual(1, employees.Count);

			var bob = employees.GetOrLookUp("bob", FindEmployee);

			Assert.AreEqual(2, employees.Count);
			Assert.AreSame(bob, employees.GetOrLookUp("bob", FindEmployee));
			Assert.AreEqual(2, employees.Count);
		}

		[Test]
		public void GetOrDefaultTest()
		{
			var joe = new Employee { Name = "joe" };
			var employees = new Dictionary<string, Employee> { { "joe", joe } };

			Assert.AreEqual(1, employees.Count);
			Assert.AreSame(joe, employees.GetOrDefault("joe"));
			Assert.AreEqual(1, employees.Count);
			Assert.IsNull(employees.GetOrDefault("bob"));
			Assert.AreEqual(1, employees.Count);
		}

		[Test]
		public void AddIfDoesNotExistTest()
		{
			var joe = new Employee { Name = "joe" };
			var employees = new Dictionary<string, Employee> { { "joe", joe } };

			Assert.AreEqual(1, employees.Count);
			employees.AddIfDoesNotExist("joe", FindEmployee);
			Assert.AreEqual(1, employees.Count);

			employees.AddIfDoesNotExist("bob", FindEmployee);

			Assert.AreEqual(2, employees.Count);
			employees.GetOrLookUp("bob", FindEmployee);
			Assert.AreEqual(2, employees.Count);
		}

		private static Employee FindEmployee(string name)
		{
			return new Employee { Name = name };
		}
	}
}
